package com.itheima.ssm.controller.advice;


import com.itheima.ssm.domain.SysLong;
import com.itheima.ssm.service.ISysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class MyLogAdvice {

    @Autowired
    private ISysLogService logService;

    @Autowired
    private HttpServletRequest request;

    @Around("execution(* com.itheima.ssm.controller.*.*(..))")
    public Object around(ProceedingJoinPoint pjp){
        Object obj = null;
        try {
            Date visitTime = new Date();
            //获取当前要增强的方法的参数
            Object[] args = pjp.getArgs();
            //放行目标方法
            obj = pjp.proceed(args);
            //保存日志
            SysLong log = new SysLong();
            log.setMethod("【类名】"+pjp.getTarget().getClass().getName()+"【方法名】"+pjp.getSignature().getName());//类名+方法名
            log.setExecutionTime(new Date().getTime()-visitTime.getTime());
            log.setIp(request.getRemoteAddr());
            log.setUrl(request.getRequestURI());
            log.setUsername(request.getRemoteUser());
            log.setVisitTime(visitTime);
            logService.saveLog(log);
        }catch (Throwable t){
            if(t.getMessage().equals("Access is denied")){
                throw new AccessDeniedException("权限不足");
            }else {
                try {
                    throw new Exception("未知异常");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            t.printStackTrace();
        }
        return obj;
    }

}
